/**
 * Created by ruby on 1/14/17.
 */

'use strict';

let config  = require('../config');
let express = require('express');
let _       = require('lodash');
//let response = require('express/lib/response'); //扩展response需要

let apiSuccess = function(){
  let message = '';
  let data = null;
  let dataPostProcess = null;

  //1、只有message
  //2、只有data

  let arguments_length = arguments.length;
  if (arguments_length == 1) {
    //只有message或者data
    if (typeof arguments[0] === 'string') {
      message = arguments[0];
    } else {
      data = arguments[0];
    }
  } else if (arguments_length == 2) {
    //message+data或者data+dataPostProcess
    if (typeof arguments[0] === 'string') {
      message = arguments[0];
      data = arguments[1];
    } else {
      data = arguments[0];
      dataPostProcess = arguments[1];
    }
  } else {
    //3个参数message、data、dataPostProcess
    message = arguments[0];
    data = arguments[1];
    dataPostProcess = arguments[2];
  }

  return apiResponse(message, config.STATUS_CODE_SUCCESS, data, dataPostProcess);
};
exports.apiSuccess = apiSuccess;

let apiFail = function(message, data = []) {
  if (typeof message !== 'string') {
    //没有message，只有data
    data = message;
    message = '';
  }

  return apiResponse(message, config.STATUS_CODE_FAIL, data, null);
};
exports.apiFail = apiFail;

let apiResponse = function(message, status, data, dataPostProcess) {
  data = data || [];
  let response_data = {};
  response_data['server_time'] = time();
  response_data['message'] = message;
  response_data['code'] = status;

  if (data) {
    if (_.isArray(data.data)) {
      //分页数据
      response_data['page'] = data.page;
      response_data['page_size'] = data.page_size;
      response_data['total_count'] = data.total_count;
      response_data['data'] = data.data;
    } else {
      response_data['data'] = data;
    }
  }

  return response_data;
};

let apiMissRequiredParams = function() {
  return apiResponse('参数不完整', config.STATUS_CODE_FAIL);
};
exports.apiMissRequiredParams = apiMissRequiredParams;

let apiNotLogin = function() {
  return apiResponse('未登录', config.STATUS_CODE_FAIL);
};
exports.apiNotLogin = apiNotLogin;


function has_empty() {
  for (let i = 0; i < arguments.length; i++) {
    if (arguments[i] === '' || arguments[i] === undefined) {
      return true;
    }
  }
  return false;
}
exports.has_empty = has_empty;

function strcmp(str1, str2) {
  return ( ( str1 == str2 ) ? 0 : ( ( str1 > str2 ) ? 1 : -1 ) );
}
exports.strcmp = strcmp;

function time() {
  return Date.now().toString().substr(0, 10);
}
exports.time = time;

//exports.response = response;